package com.shortvedio.content.service.imp;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.shortvedio.base.exception.ShortVedioPlusException;
import com.shortvedio.base.mapper.ClassifyMapper;
import com.shortvedio.base.mapper.UserInterestMapper;
import com.shortvedio.base.model.Result;
import com.shortvedio.base.model.po.Classify;
import com.shortvedio.base.model.po.UserInterest;
import com.shortvedio.content.es.ClassifyDoc;
import com.shortvedio.content.service.ClassifyService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;

@Service
@Slf4j
public class ClassifyServiceImpl implements ClassifyService {

    @Autowired
    ClassifyMapper classifyMapper;

    @Autowired
    UserInterestMapper userInterestMapper;


    @Autowired
    private RestHighLevelClient client;

    @Override
    @Transactional
    public Result addClassify(Classify classify) {
        //搜索
        LambdaQueryWrapper<Classify> classifyLambdaQueryWrapper = new LambdaQueryWrapper<>();
        classifyLambdaQueryWrapper.eq(Classify::getName,classify.getName());
        Classify classifyDb = classifyMapper.selectOne(classifyLambdaQueryWrapper);
        if (classifyDb!=null){
            return Result.error("已经有该分类");
        }

        int insert = classifyMapper.insert(classify);
        if (insert<=0){
            return Result.error("添加分类失败");
        }
        Boolean aBoolean = addClassifyToEs(classify);
        if (!aBoolean){
            ShortVedioPlusException.cast("失败请重新上传");
        }
        return Result.success("添加分类成功");
    }

    @Override
    @Transactional
    public Result deleteClassify(Long classifyId,Long userId) throws IOException {
        Classify classify = classifyMapper.selectById(classifyId);
        log.info("userId1:{},userId2:{}",userId,classify.getUserId());
        if (!classify.getUserId().equals(userId)){
            return Result.error("不是你创建的标签请不要删除");
        }
        int delete = classifyMapper.deleteById(classifyId);
        if (delete<=0){
            return Result.error("删除失败");
        }
        deleteClassify(classifyId);
        return Result.success("删除成功");
    }

    @Override
    public Result addUserInterest(Long userId, Long classifyId) {//添加用户兴趣
        LambdaQueryWrapper<UserInterest> userInterestLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userInterestLambdaQueryWrapper.eq(UserInterest::getUserId,userId).eq(UserInterest::getType,classifyId);
        UserInterest userInterest = userInterestMapper.selectOne(userInterestLambdaQueryWrapper);
        if (userInterest!=null){
            return Result.error("已经存在该兴趣请不要重复添加");
        }
        UserInterest userInterestToDb = new UserInterest();
        userInterestToDb.setUserId(userId);
        userInterestToDb.setType(classifyId);
        int insert = userInterestMapper.insert(userInterestToDb);
        if (insert<=0){
            return Result.error("添加失败");
        }
        return Result.success("添加成功");
    }

    private void deleteClassify(Long classifyId) throws IOException {
        // 1.准备Request
        DeleteRequest request = new DeleteRequest("classify", classifyId.toString());
        // 2.发送请求
        client.delete(request, RequestOptions.DEFAULT);
    }


    Boolean addClassifyToEs(Classify classify){//添加到es
        ClassifyDoc classifyDoc = new ClassifyDoc(classify);
        // 3.将Doc转json
        String json = JSON.toJSONString(classify);
        // 准备Request对象
        IndexRequest request = new IndexRequest("classify").id(classify.getId().toString());
        // 准备Json文档
        request.source(json, XContentType.JSON);
        //发送请求
        try {
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            return false;
        }
        return true;
    }
}
